<template>
  <el-form
      :model="form"
      label-width="90px"
      style="width: 400px; margin: 80px auto;"
      @submit.prevent="doRegister"
  >
    <h2 style="text-align: center; margin-bottom: 30px;">多角色注册</h2>

    <!-- 用户名 -->
    <el-form-item label="用户名" prop="loginName">
      <el-input
          v-model="form.loginName"
          placeholder="请输入用户名/工号"
          clearable
      />
    </el-form-item>

    <!-- 密码 -->
    <el-form-item label="密码" prop="password">
      <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          clearable
          show-password
      />
    </el-form-item>

    <!-- 角色 -->
    <el-form-item label="角色" prop="role">
      <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
        <el-option label="管理员" value="admin" />
        <el-option label="护工" value="caregiver" />
        <el-option label="前台" value="reception" />
        <el-option label="家属" value="family" />
      </el-select>
    </el-form-item>

    <!-- 真实姓名 -->
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name" placeholder="请输入真实姓名" clearable />
    </el-form-item>

    <!-- 手机号 -->
    <el-form-item label="手机号" prop="phone">
      <el-input
          v-model="form.phone"
          placeholder="请输入手机号"
          clearable
          maxlength="11"
      />
    </el-form-item>

    <!-- 老人ID（仅家属） -->
    <el-form-item
        v-if="form.role === 'family'"
        label="关联老人ID"
        prop="elderId"
    >
      <el-input
          v-model.number="form.elderId"
          placeholder="请输入老人ID"
          clearable
      />
    </el-form-item>

    <!-- 按钮 -->
    <el-form-item>
      <el-button type="success" native-type="submit" :loading="loading">
        注册
      </el-button>
      <el-button @click="$router.push('/login')">返回登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { register } from '@/api/auth.js'
import { ElMessage } from 'element-plus'

const loading = ref(false)

const form = reactive({
  loginName: '',
  password: '',
  role: 'admin',
  name: '',
  phone: '',
  elderId: null
})

const doRegister = async () => {
  // 简单校验
  if (!form.loginName || !form.password || !form.name || !form.phone) {
    ElMessage.warning('请完整填写信息')
    return
  }
  if (form.role === 'family' && !form.elderId) {
    ElMessage.warning('家属注册必须填写关联老人ID')
    return
  }

  loading.value = true
  try {
    const res = await register(form)
    if (res.data.code === 200) {
      ElMessage.success('注册成功！即将跳转登录页')
      setTimeout(() => {
        location.href = '/login'
      }, 1000)
    } else {
      ElMessage.error(res.data.msg || '注册失败')
    }
  } catch (e) {
    ElMessage.error('网络异常：' + e.message)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 居中微调 */
.el-form-item {
  margin-bottom: 22px;
}
</style>
